package com.insightg3.android;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.api.translate.Language;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;

public class SearchResultActivity extends Activity {
	private ArrayList<SearchResultStatus> list = null;
	private SearchResultAdapter adapter = null;
	
	//-------------------- initial variable
    private static String searchKey = "";
    private static long startPrice = 0;
    private static long endPrice = 100000000;
    private static String orderBy = "price:asc";
	private static long totalNum = 0l;
	private static int pageNum = 0;
	private static long searchNo = 1;
	protected static String testUrl = "http://gw.api.taobao.com/router/rest";
	protected static String appkey = "12201364";
	protected static String secret = "89ec79f08a30ab437e0c8e8fc05d8349";

    public void getTaobao(String target, long searchNo, long startPrice, long endPrice, String orderBy) {
    	this.list = new ArrayList<SearchResultStatus>();
    	pageNum = 0;
    	if(searchNo < 1) searchNo = 1;
    	String q = target;
    	String result = Util.getResult(testUrl, GetTaobaoResult.testUserGet(q, searchNo, startPrice, endPrice, orderBy));
    	if(result != null) {
    		Log.d("TaoBao search result:", result);
    		try {
    			JSONObject jb = new JSONObject(result);
    			SearchResultStatus srs = null;
    			jb = jb.getJSONObject("items_get_response");
    			totalNum = Long.parseLong(String.valueOf(jb.get("total_results")));    			
    			jb = jb.getJSONObject("items");
    			JSONArray jItems = jb.getJSONArray("item");		
    			System.out.println("Init");
    			for(int i = 0; i < jItems.length(); i++) {
    				srs = new SearchResultStatus();
    				JSONObject jItem = (JSONObject) jItems.get(i);
    				srs.setTitle(((String) jItem.get("title")).replace("<span class=H>", "").replace("</span>", ""));
    				srs.setPrice((String) jItem.get("price"));
    				srs.setImage((String) jItem.get("pic_url"));
    				pageNum++;
    				list.add(srs);
    			}
    		} catch (JSONException e) {
    			e.printStackTrace();
			}
    	} else {
			totalNum = 0l;
			pageNum = 0;
			SearchResultActivity.searchNo = 0;
		}
    }
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_result_listview);
		ListView listview = (ListView) findViewById(R.id.lvResult);

		//-------------------- get search optional
		if(( savedInstanceState == null ) || ( savedInstanceState.isEmpty()) ) {
			searchKey = getIntent().getExtras().getString("SEARCH_KEY");
			try {
				if(getIntent().getExtras().getString("SEARCH_ORD") != null && getIntent().getExtras().getString("SEARCH_ORD").equals("Descend")) {
					orderBy = "price:desc";
				} else {
					orderBy = "price:asc";
				}
				if(getIntent().getExtras().getString("SEARCH_NO") != null && !getIntent().getExtras().getString("SEARCH_NO").equals("")) {
					searchNo = Long.parseLong(getIntent().getExtras().getString("SEARCH_NO"));
				} else {
					searchNo = 1;
				}
				if(getIntent().getExtras().getString("SEARCH_MIN") != null && !getIntent().getExtras().getString("SEARCH_MIN").equals("")) {
					startPrice = Long.parseLong(getIntent().getExtras().getString("SEARCH_MIN"));
				} else {
					startPrice = 0;
				}
				if(getIntent().getExtras().getString("SEARCH_MAX") != null && !getIntent().getExtras().getString("SEARCH_MAX").equals("")) {
					endPrice = Long.parseLong(getIntent().getExtras().getString("SEARCH_MAX"));
				} else {
					endPrice = 100000000; 
				}
			} catch(NumberFormatException e) {
				searchNo = 1;
				startPrice = 0;
				endPrice = 100000000;
				orderBy = "price:asc";
			}
		}
		((AndroidApplication)getApplication()).setSelectedItems(null);
		TextView textview = (TextView) findViewById(R.id.txtResultTitle);
		
		//----------------------------------- search
		if(searchKey != null && !searchKey.equals("")) {
			Log.d("Optional", searchKey + ", " + orderBy + ", " + searchNo + ", " + startPrice + ", " + endPrice);
			getTaobao(searchKey, searchNo, startPrice, endPrice, orderBy);
			textview.setText("Total Result is " + totalNum + " items, this is page " + searchNo);
		}
		adapter = new SearchResultAdapter(this, R.layout.main_result_row, list);
		listview.setAdapter(adapter);
		
		// Create Menu
		listview.setOnItemClickListener(new OnItemClickListener() {
			@Override  
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,  
			long arg3) {  
				setTitle("Click"+arg2+" Item");  
			}  
		});
		listview.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
			@Override  
			public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {  
			menu.setHeaderTitle("LongTouch-ContextMenu");     
			menu.add(0, 0, 0, "same key search in Japan");  
			menu.add(0, 1, 0, "select to compare list");     
			menu.add(0, 2, 0, "to register keyword");
			} 
		});

		((Button) findViewById(R.id.PrevPage)).setOnClickListener(btnPrevListener);
		((Button) findViewById(R.id.NextPage)).setOnClickListener(btnNextListener); 
	}

	@Override  
	public boolean onContextItemSelected(MenuItem item) {  
		setTitle("Long touch "+item.getItemId()+" Item");
		Intent intent = null;
		switch(item.getItemId()){
		case 0:
			//search in TaoBao
			String key = AndroidUtils.translateString(searchKey, Language.CHINESE_SIMPLIFIED, Language.JAPANESE);
			intent = new Intent( SearchResultActivity.this, KakakuSearchResultActivity.class );
			intent.putExtra( "SEARCH_KEY", key);
			intent.putExtra("SEARCH_NO", "1");
			intent.putExtra("SEARCH_MIN", String.valueOf(startPrice));
			intent.putExtra("SEARCH_MAX", String.valueOf(endPrice));
			if(orderBy.equals("price:desc")) {
				intent.putExtra("SEARCH_ORD", "Descend");
				Log.d("Optional", key + ", " + "Descend" + ", 1, " + startPrice + ", " + endPrice);
			} else {
				intent.putExtra("SEARCH_ORD", "");
				Log.d("Optional", key + ", " + "" + ", 1, " + startPrice + ", " + endPrice);
			}
			startActivity( intent );
			break;
		case 1:
			ListView listview = (ListView) findViewById(R.id.lvResult);
			int size = listview.getChildCount();
			for (int i = 0; i < size; i++) {
				final View listDataView = listview.getChildAt(i);
				CheckBox chkSelect = (CheckBox) listDataView.findViewById(R.id.chkSelect);
				if (chkSelect.isChecked()) {
					((AndroidApplication)getApplication()).addSelectedItem(list.get(i));
					Log.d("selected item is:", list.get(i).toString() +";summay"+list.get(i).getSummary());
				}
			}
			List<SearchResultStatus> selectedItems = ((AndroidApplication)getApplication()).getSelectedItems();
			Log.d("selected items is :", selectedItems.toString());
			intent = new Intent( SearchResultActivity.this, CompareResultActivity.class );
			startActivity( intent );
			break;
		case 2:
			intent = new Intent( SearchResultActivity.this, KeywordRegisterActivity.class );
			startActivity( intent );
			break;
		}

		return super.onContextItemSelected(item);  
	}  
	
	OnClickListener btnPrevListener = new OnClickListener() {
		public void onClick(View v) {
			if(searchNo > 1) {
				TextView textview = (TextView) findViewById(R.id.txtResultTitle);
				searchNo--;
				if(searchKey != null && !searchKey.equals("")) {
					getTaobao(searchKey, searchNo, startPrice, endPrice, orderBy);
					textview.setText("Total Result is " + totalNum + " items, this is page " + searchNo);
				}
				ListView listview = (ListView) findViewById(R.id.lvResult);
				adapter = new SearchResultAdapter(SearchResultActivity.this, R.layout.main_result_row, list);
				listview.setAdapter(adapter);
			}
		}
	};

	OnClickListener btnNextListener = new OnClickListener() {
		public void onClick(View v) {
			if(searchNo * 10 < totalNum && searchNo < 100) {
				TextView textview = (TextView) findViewById(R.id.txtResultTitle);
				searchNo++;
				if(searchKey != null && !searchKey.equals("")) {
					getTaobao(searchKey, searchNo, startPrice, endPrice, orderBy);
					textview.setText("Total Result is " + totalNum + " items, this is page " + searchNo);
				}
				ListView listview = (ListView) findViewById(R.id.lvResult);
				adapter = new SearchResultAdapter(SearchResultActivity.this, R.layout.main_result_row, list);
				listview.setAdapter(adapter);
			}
		}
	};
}